'use strict';

const db = uniCloud.database();

exports.main = async (event, context) => {
  const { mobile, type } = event; // type: 'register' | 'login' | 'reset'
  
  // 参数校验
  if (!mobile || !type) {
    return {
      code: 400,
      message: '手机号和类型为必填项'
    };
  }
  
  // 手机号格式校验
  const mobileRegex = /^1[3-9]\d{9}$/;
  if (!mobileRegex.test(mobile)) {
    return {
      code: 400,
      message: '手机号格式错误'
    };
  }
  
  // 类型校验
  const validTypes = ['register', 'login', 'reset'];
  if (!validTypes.includes(type)) {
    return {
      code: 400,
      message: '验证码类型错误'
    };
  }
  
  try {
    const clientIP = context.CLIENTIP || '0.0.0.0';
    const now = new Date();
    const codeCollection = db.collection('sms-codes');
    
    // 检查1分钟内是否已发送验证码
    const recentCodeRes = await codeCollection.where({
      mobile: mobile,
      ip: clientIP,
      create_time: db.command.gt(new Date(now.getTime() - 60000)) // 1分钟内
    }).get();
    
    if (recentCodeRes.data.length > 0) {
      return {
        code: 429,
        message: '请勿频繁发送验证码，请1分钟后再试'
      };
    }
    
    // 检查今日发送次数（防止刷验证码）
    const todayStart = new Date();
    todayStart.setHours(0, 0, 0, 0);
    const todayCodeRes = await codeCollection.where({
      mobile: mobile,
      create_time: db.command.gt(todayStart)
    }).get();
    
    if (todayCodeRes.data.length >= 10) {
      return {
        code: 429,
        message: '今日发送次数已达上限，请明日再试'
      };
    }
    
    // 注册时检查手机号是否已存在
    if (type === 'register') {
      const userCollection = db.collection('uni-id-users');
      const existUser = await userCollection.where({
        mobile: mobile
      }).get();
      
      if (existUser.data.length > 0) {
        return {
          code: 400,
          message: '该手机号已注册'
        };
      }
    }
    
    // 登录时检查手机号是否存在
    if (type === 'login') {
      const userCollection = db.collection('uni-id-users');
      const existUser = await userCollection.where({
        mobile: mobile
      }).get();
      
      if (existUser.data.length === 0) {
        return {
          code: 400,
          message: '该手机号尚未注册'
        };
      }
    }
    
    // 生成6位随机验证码
    const code = Math.floor(100000 + Math.random() * 900000).toString();
    
    // 过期时间：5分钟
    const expireTime = new Date(now.getTime() + 5 * 60 * 1000);
    
    // 保存验证码记录
    const codeData = {
      mobile: mobile,
      code: code,
      type: type,
      create_time: now,
      expire_time: expireTime,
      used: false,
      ip: clientIP
    };
    
    const saveResult = await codeCollection.add(codeData);
    
    if (!saveResult.id) {
      return {
        code: 500,
        message: '验证码生成失败，请重试'
      };
    }
    
    // 实际项目中这里应该调用短信服务商API发送短信
    // 这里模拟发送成功
    console.log(`向手机号 ${mobile} 发送验证码: ${code}`);
    
    // 开发环境下返回验证码用于测试，生产环境应该移除
    const responseData = {
      message: '验证码发送成功',
      expire_minutes: 5
    };
    
    // 开发环境下可以返回验证码便于测试
    if (process.env.NODE_ENV === 'development') {
      responseData.code = code;
    }
    
    return {
      code: 200,
      data: responseData
    };
    
  } catch (error) {
    console.error('发送验证码错误：', error);
    return {
      code: 500,
      message: '服务器错误，请重试'
    };
  }
};